package me.monster.smarttraffic.tool;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


/**
 * @description
 * @author: Created jiangjiwei in 2018/11/1 12:25
 */
public class Util {
    private static final ActivityLifecycleImpl ACTIVITY_LIFECYCLE = new ActivityLifecycleImpl();

    private static Application sApplication;

    private Util() {
        throw new UnsupportedOperationException("can't instantiate me");
    }

    /**
     * 使用 非 Application 的 Context 进行初始化
     *
     * @param context Context
     */
    public static void init(@NonNull final Context context) {
        init((Application) context.getApplicationContext());
    }

    /**
     * 使用 Application 类型的 Context 进行初始化
     *
     * @param application application
     */
    public static void init(@NonNull final Application application) {
        if (sApplication == null) {
            Util.sApplication = application;
            Util.sApplication.registerActivityLifecycleCallbacks(ACTIVITY_LIFECYCLE);
        }
    }

    /**
     * 获取 Application 对象
     *
     * @return Application
     */
    public static Application getApp() {
        if (sApplication != null) {
            return sApplication;
        }
        try {
            @SuppressLint("PrivateApi")
            Class<?> activityThread = Class.forName("android.app.ActivityThread");
            Object at = activityThread.getMethod("currentActivityThread").invoke(null);
            Object app = activityThread.getMethod("getApplication").invoke(at);
            if (app == null) {
                throw new NullPointerException("u should init first");
            }
            init((Application) app);
            return sApplication;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        throw new NullPointerException("u should init first");
    }

    /**
     * 获取自定义的 Activity 生命周期管理器 ACTIVITY_LIFECYCLE
     *
     * @return ACTIVITY_LIFECYCLE
     */
    static ActivityLifecycleImpl getActivityLifecycle() {
        return ACTIVITY_LIFECYCLE;
    }

    /**
     * 获取未被销毁的 Activity 集合
     *
     * @return Activity List
     */
    public static LinkedList<Activity> getActivityList() {
        return ACTIVITY_LIFECYCLE.mActivityLinkedList;
    }

    /**
     * 返回最上层的 Activity 类型的 Context ，如果当前 App 不处于 前台，则返回 Application 类型的 Context
     *
     * @return Context
     */
    public static Context getTopActivityOrApp() {
        if (isAppForeground()) {
            Activity topActivity = ACTIVITY_LIFECYCLE.getTopActivity();
            return topActivity == null ? getApp() : topActivity;
        } else {
            return getApp();
        }
    }

    public static Activity getTopActivity() {
        return ACTIVITY_LIFECYCLE.getTopActivity();
    }

    /**
     * 判断当前 Application 是否处于前台
     *
     * @return false or true
     */
    public static boolean isAppForeground() {
        ActivityManager activityManager = (ActivityManager) Util.getApp().getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager == null) {
            return false;
        }
        List<ActivityManager.RunningAppProcessInfo> infoList = activityManager.getRunningAppProcesses();
        if (infoList == null || infoList.size() == 0) {
            return false;
        }
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : infoList) {
            if (runningAppProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return runningAppProcessInfo.processName.equals(getApp().getPackageName());
            }
        }
        return false;
    }


    public interface OnAppStatusChangedListener {
        /**
         * 当 Activity 位于前台
         */
        void onForeground();

        /**
         * 当 Activity 位于后台
         */
        void onBackground();
    }

    static class ActivityLifecycleImpl implements Application.ActivityLifecycleCallbacks {

        final LinkedList<Activity> mActivityLinkedList = new LinkedList<>();
        final HashMap<Object, OnAppStatusChangedListener> mActivityStatusListenerMap = new HashMap<>();

        private int visibleActivityCount;
        private int uetoolDismissY = -1;

        private int mForegroundNum = 0;
        private int mConfigNum = 0;

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            setTopActivity(activity);
        }

        @Override
        public void onActivityStarted(Activity activity) {

            visibleActivityCount++;
            if (visibleActivityCount == 1 && uetoolDismissY >= 0) {
//                if (BuildConfig.DEBUG) {
//                    UETool.showUETMenu(uetoolDismissY);
//                }
            }

            setTopActivity(activity);
            if (mForegroundNum <= 0) {
                postStatus(true);
            }
            if (mConfigNum < 0) {
                ++mConfigNum;
            } else {
                ++mForegroundNum;
            }
        }

        @Override
        public void onActivityResumed(Activity activity) {
            setTopActivity(activity);
        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

            visibleActivityCount--;
//            if (visibleActivityCount == 0) {
//                uetoolDismissY = UETool.dismissUETMenu();
//            }

            if (activity.isChangingConfigurations()) {
                --mConfigNum;
            } else {
                --mForegroundNum;
                if (mForegroundNum <= 0) {
                    postStatus(false);
                }
            }
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            mActivityLinkedList.remove(activity);
        }

        Activity getTopActivity() {
            if (!mActivityLinkedList.isEmpty()) {
                final Activity topActivity = mActivityLinkedList.getLast();
                if (topActivity != null) {
                    return topActivity;
                }
            }
            try {
                @SuppressLint("PrivateApi") Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
                Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
                Field activitiesField = activityThreadClass.getDeclaredField("mActivityList");
                activitiesField.setAccessible(true);
                Map activities = (Map) activitiesField.get(activityThread);
                if (activities == null) {
                    return null;
                }
                for (Object o : activities.values()) {
                    Class activityClass = o.getClass();
                    Field pausedClassField = activityClass.getDeclaredField("paused");
                    pausedClassField.setAccessible(true);
                    if (!pausedClassField.getBoolean(o)) {
                        Field activityField = activityClass.getDeclaredField("activity");
                        activityField.setAccessible(true);
                        Activity activity = (Activity) activityField.get(activityField);
                        setTopActivity(activity);
                        return activity;
                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            return null;
        }

        void setTopActivity(Activity topActivity) {
            if (mActivityLinkedList.contains(topActivity)) {
                if (!mActivityLinkedList.getLast().equals(topActivity)) {
                    mActivityLinkedList.remove(topActivity);
                    mActivityLinkedList.addLast(topActivity);
                }
            } else {
                mActivityLinkedList.addLast(topActivity);
            }
        }

        private void postStatus(boolean isForeground) {
            if (mActivityStatusListenerMap.isEmpty()) {
                return;
            }
            for (OnAppStatusChangedListener onAppStatusChangedListener : mActivityStatusListenerMap.values()) {
                if (onAppStatusChangedListener == null) {
                    return;
                }
                if (isForeground) {
                    onAppStatusChangedListener.onBackground();
                } else {
                    onAppStatusChangedListener.onBackground();
                }
            }
        }
    }
}
